const net = require('net')
const mysql = require('mysql')
//数据库配置
const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'klren0312',
  database: 'rain',
  port: 3306
})
//连接数据库
conn.connect()

net.createServer(function(socket) {
  socket.on('data', function(data) {
    if (data) {
      socket.write('接受到了你的数据: ' + data)
      try {
        const res = JSON.parse(data)
        Object.keys(res).forEach(d => {
          let obj = {}
          if (d === 'isOpen') {
            const openObj = { status: res[d] === '1' ? 1 : 0 }
            conn.query('INSERT INTO rainshed SET ?', openObj, function(error, result, fields) {
              if (error) throw error;
            })
          } else {
            obj.name = d
            obj.value = res[d]
            conn.query('INSERT INTO sensor SET ?', obj, function(error, result, fields) {
              if (error) throw error;
            })
          }
        })
      } catch (error) {
        
      }
    }
  })
  socket.on('end', function(data) {
    console.log('end')
  })

  socket.on('error', function() {
  })
  socket.write('ready to receive your msg')
}).listen(8848)
